package com.example.demo.practice.devices;


import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.DialogPreference;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

import com.example.demo.practice.R;
import com.example.demo.practice.SettingActivity;
import com.example.demo.practice.innerclass.IBaseActivity;
import com.example.demo.practice.tool.ServerHttp;
import com.example.demo.practice.ui.MapAndList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;


public class Inspection extends IBaseActivity {
    private MapAndList mapAndList;
    private List<String> geoJson;
    private List<String> GeoJson;
    private ImageView returned;

    private LocationManager locationManager;
    private LocationListener locationListener;

    private Button starts;
    private Button write;
    private Button stops;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspection);
        setTitle("消防巡检");

        starts = (Button) findViewById(R.id.starts);
        write = (Button) findViewById(R.id.write);
        stops = (Button) findViewById(R.id.stops);
        returned = (ImageView)findViewById(R.id.returned);

        returned.setOnClickListener(new ImageView.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(Inspection.this, SettingActivity.class);
                startActivity(intent);
                finish();
            }
        });

        starts.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                locate();
                write.setVisibility(VISIBLE);
                stops.setVisibility(VISIBLE);
                starts.setVisibility(GONE);
            }
        });

        write.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(Inspection.this,InspectionQuestion.class);
                startActivity(intent);
            }
        });

        stops.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                showDialog();
            }
        });

        mapAndList = (MapAndList) findViewById(R.id.mapAndList);
        mapAndList.loadUrl("html/devices/Inspection.html");
        serverHttp=new ServerHttp(new UpdateList());
        serverHttp.setUrl("getInspection");

    }

    class UpdateList extends Handler{
        @Override
        public void handleMessage(Message msg) {
            JSONArray jsonArray=serverHttp.getData();
            geoJson=new ArrayList<>();
            List<Map<String, Object>> groupArray = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < jsonArray.length(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject json = null;
                try {
                    json = (JSONObject) jsonArray.get(i);
                    map.put("worker", json.getString("worker"));
                    String Time = json.getString("date");
                    String[] AuditDates = Time.split("T");
                    map.put("date", "任务时间：" + AuditDates[0]);
                    geoJson.add(json.getString("st_asgeojson"));
                    groupArray.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jsonArray = null;
            serverHttp.clear();
            //适配列表

            SimpleAdapter simpleAdapter = new SimpleAdapter(Inspection.this,
                    groupArray,
                    R.layout.inspection_item,
                    new String[]{"worker","date"},
                    new int[]{R.id.worker, R.id.date});
            mapAndList.setListAdapter(simpleAdapter);
            mapAndList.setItemClickListener(new SingleClick());
            super.handleMessage(msg);
        }

    }

    public class SingleClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String json = geoJson.get(i);
            Log.e("ss",json);
            starts.setEnabled(true);
            mapAndList.drawLine(json);
        }
    }

    /**
     * 开始定位
     */
    private void locate() {
            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            //ACCURACY_HIGH/ACCURACY_LOW精度选择
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            //高度
            criteria.setAltitudeRequired(true);
            //方位信息
            criteria.setBearingRequired(true);
            //是否允许付费
            criteria.setCostAllowed(true);
            //对电量的要求
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            //速度
            criteria.setSpeedRequired(true);
            String locationProvider = locationManager.getBestProvider(criteria, true);
            if (ActivityCompat.checkSelfPermission(Inspection.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Inspection.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.e("定位", "没有定位权限");
            } else {
                if (locationProvider != null) {
                    Location location = locationManager.getLastKnownLocation(locationProvider);
                    addMarker(location);
                }
                locationListener = new locateListener();
                locationManager.requestLocationUpdates(locationProvider, 1000, 1, locationListener);
            }
    }
    /**
     * 位置监听
     */
    public class locateListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            addMarker(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }

    /**
     * 添加地图定位图标
     * @param location
     */
    private void addMarker(Location location) {
        if (location!=null){
            Log.e("定位","非空");
            //添加路线进巡检轨迹
            //GeoJson.add(???????????);
            double lng = location.getLongitude();
            double lat = location.getLatitude();
            mapAndList.setMapCenter(lat, lng);
        }
        else {
            Log.e("定位","空");
            return;
        }
    }

    private void showDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("停止巡检并发送巡检路线？");
        builder.setPositiveButton("确认",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //
                //发送巡检路线
                starts.setVisibility(VISIBLE);
                write.setVisibility(GONE);
                stops.setVisibility(GONE);
                showDialog2();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }

    private void showDialog2(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("已发送！");
        builder.setPositiveButton("确认",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }
}
